<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    @dialog-close="dialogClose"
    :dialogWidth="dialogWidth"
  >
    <template #searchPanel>
      <el-row :gutter="20">
        <search-panel
          v-slot="{ form }"
          @search="search"
          :showAddButton="true"
          :showExportButton="true"
          @insert="addOrEditService"
          @export="handleDataExport('Subscribe','预约数据')"
          :excelPer="'subscribe:export'"
          :addPer="'subscribe:save'"
          :selectPer="'subscribe:page'"
          addTitle="新增预约"
          :showSendButton="true"
          sendButtonTitle="预约设置"
          @send="appointmentSettingsChange"
        >
          <job-shop
            v-model="form.storeId"
            placeholder="所属门店"
          />
          <el-date-picker
            v-model="form.subscribeDate"
            type="date"
            placeholder="选择预约时间"
            value-format="yyyy-MM-dd"
            clearable
          >
          </el-date-picker>
          <el-input
            clearable
            style="width: 200px"
            v-model="form.clientInfoAndSubscribeCode"
            placeholder="请输入客户姓名/手机号/预约编号"
          />
        </search-panel>
      </el-row>
    </template>
    <template #contentPanel>
      <data-table
        :value="tableData"
        :has-action="true"
        :table-column-attributes="tableColumnAttributes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :total-count="totalCount"
        :width="160"
        :isShowPage="true"
        @row-dblclick="appointmentDetails"
      >
        <template #action="{ row }">
          <i
            class="el-icon-edit"
            title="修改"
            v-permission="'subscribe:update'"
            style="margin-left: 15px; cursor: pointer"
            @click="addOrEditService(row)"
          ></i>
          <i
            class="el-icon-delete"
            title="删除"
            v-permission="'subscribe:del'"
            style="color: red; margin-left: 15px; cursor: pointer"
            @click="handleDataDelete(row)"
          ></i>
        </template>
      </data-table>
    </template>
    <template #dialog>
      <dialog-view-detail
        v-if="dialogTitle=='预约详情'"
        :value="dialogData"
        @operate="handleDataOperateChange"
      />
      <AppointmentSettings @close="dialogClose" v-if="dialogTitle=='预约设置'" />
    </template>
  </base-layout>
</template>

<script>
import {
  subscribeList,
  deleteSubscribe,
  affirmSubscribe,
  cancelSubscribe,
  turnWorkOrderSubscribe,
} from '@/api/after-sale/customer-center/index'
import baseMixin from '@/mixins/base'
import ElFormItem from 'element-ui/packages/form/src/form-item.vue'
import ElRow from 'element-ui/packages/row/src/row'
import ElCol from 'element-ui/packages/col/src/col'
import { parseTimeToYMDHMS, parseTime,exportExcel } from '@/utils'
import DialogViewDetail from './view/index.vue'
import AppointmentSettings from './AppointmentSettings';

export default {
  components: {
    ElCol,
    ElRow,
    ElFormItem,
    DialogViewDetail,
    AppointmentSettings,
  },
  mixins: [
    baseMixin({
      findData: subscribeList,
      deleteData: deleteSubscribe,
      dataName: ['content', 'totalRecords'],
      isAdd: false,
      idName: 'id',
      format (res) {
        return res.map((data) => {
          data.createTime = parseTimeToYMDHMS(data.createTime)
          if (data.lastLoginTime) {
            data.lastLoginTime = parseTimeToYMDHMS(data.lastLoginTime)
          }
          data.subscribeDate = parseTime(data.subscribeDate) + ' ' + data.visitTime
          if (data.birthday) {
            data.birthday = parseTime(data.birthday)
          }
          return data
        })
      },
    }),
  ],
  data () {
    return {
      dict: {},
      dialogVisible: false,
      communitys: [],
      dialogWidth: '1100px',
      service: {},
      isAdd: false,
      tableColumnAttributes: [
        { name: '所属门店', value: 'storeName', type: 'text' },
        { name: '预约编号', value: 'subscribeCode', type: 'text' },
        { name: '客户名称', value: 'clientName', type: 'text' },
        { name: '手机号', value: 'phone', type: 'text', width: '100px' },
        { name: '车牌号', value: 'licensePlateNumber', type: 'text' },
        { name: '性别', value: 'genderCst', type: 'text' },
        { name: '预约项目', value: 'carProjectNames', type: 'text' },
        { name: '预约到店', value: 'subscribeDate', type: 'text', width: '200px' },
        // { name: '保险到期', value: 'insureExpireDate', type: 'text' },
        { name: '预约来源', value: 'subscribeType', type: 'text' },
        { name: '状态', value: 'status', type: 'text' },
        { name: '预约接待', value: 'userName', type: 'text' },
        { name: '预约备注', value: 'remark', type: 'text' },
        { name: '录入时间', value: 'createTime', type: 'text' },
        { name: '录入人', value: 'enteringUserName', type: 'text' },
      ],
    }
  },
  async created () { },
  methods: {
    //预约详情事件处理
    handleDataOperateChange (data) {
      console.log('调阅信息', data)
      if (data.type == 1) {
        this.dialogClose();
        this.setTableData();
        return
      }
      let { type, carryInformation } = data;
      // type 2 确认 3 工单 4 取消
      let option = {
        id: carryInformation.id,
        status: type == 2 ? '等待到店' : type == 4 ? '预约取消' : '已转工单',
      }
      this.$confirm("是否确认操作", '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.actionFunction(type, option, data);
        })
    },
    async actionFunction (type, option, data) {
      let { success } = type == 2 ? await affirmSubscribe(option) : type == 4 ? await cancelSubscribe(option) : await turnWorkOrderSubscribe(option.id);
      if (success) {
        this.$message.success('操作成功');
        //如果类3 预约转工单
        if (type == 3) {
          let arry = [
            { key: '快速单', type: 1, path: '/workOrderManage/create-fast' },
            { key: '综合单', type: 3, path: '/workOrderManage/create-comprehensive' },
            { key: '洗车单', type: 2, path: '/workOrderManage/create-car-wash' },
            { key: '销售单', type: 5, path: '/workOrderManage/create-sell' },];
          let orderTarge = {};
          arry.forEach(item => {
            if (item.key == data.carryInformation.subscribeWorkOrderDictValue) {
              orderTarge = item
            }
          })
          if (Object.keys(orderTarge).length > 0) {
            data.carryInformation.id = '';
            sessionStorage.setItem('pendingWorkOrder', JSON.stringify({ ...data, ...orderTarge, }));//暂存待转工单信息
            this.$router.push({
              path: orderTarge.path,
            })
          }
          return;
        }
        this.dialogClose();
        this.setTableData();
      }
    },
    //预约详情
    appointmentDetails (row) {
      this.dialogVisible = true;
      this.dialogTitle = '预约详情';
      this.dialogData = row;
    },
    //预约设置
    appointmentSettingsChange () {
      this.dialogVisible = true;
      this.dialogTitle = '预约设置';
    },
    search (form) {
      this.searchOptions = {
        ...form
      }
      this.currentPage = 1
      this.setTableData()
    },
    //新增或者编辑
    addOrEditService (row) {
      let path = `/customer-center/${row ? 'edit-appointment' : 'create-appointment'}`;
      this.$router.push({
        path: path, query: {
          id: row ? row.id : '',
        }
      })
    },
    interestsInfo (row, type) {
      this.$store.state.customerInfoId = row.id
      this.$store.state.customerInfotype = type
      this.$router.push({ path: '/customer/customerInfo' })
    },
    getAdverts (row) {
      getcategory(row.id).then((result) => {
        if (result.code == '0') {
          this.advert = result.data
          this.handleDataChange(row)
        }
      })
    },

    carInfo (row) {
      this.$store.state.customerCarInfoId = row.id
      this.$store.state.carInfoId = ''
      this.$store.state.carInfotype = 0
      this.$router.push({ path: '/customer/carInfo' })
    },
  },
}
</script>

<style lang="scss" scoped>
.vLine {
  border-left: solid 3px black;
  height: 16px;
  vertical-align: bottom;
  display: inline-block;
}
</style>
